package com.ny.zmb.openapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ny.zmb.openapi.config.YsConfig;
import com.ny.zmb.openapi.controller.entity.*;
import com.ny.zmb.openapi.entity.PmStoreYs;
import com.ny.zmb.openapi.gMdemo.Common;
import com.ny.zmb.openapi.gMdemo.YsfApi;
import com.ny.zmb.openapi.gMdemo.bean.WxBizContent;
import com.ny.zmb.openapi.mapper.PmStoreYsMapper;
import com.ny.zmb.openapi.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author yangx
 * @description 聚合收银台下单接口
 * @date 2021/10/9
 */
@Slf4j
@RestController
@CrossOrigin
public class PayShangHuJin {

    @Resource
    private YsfApi ysfApi;


    private static final String ALLCHAR = "0123456789ABCDEF";

    /**
     * 发起方商户号 服务商在银盛给自己开设的商户号，即可当作发起方商户号
     * 生产环境需要使用自己的发起发商户号，并找相应的对接人员开通所需要的接口权限，并告知是国密还是RSA
     */
    private static final String CERT_ID = "826513173750017";

    /**
     * 商户端私钥证书密码
     * 生产环境需要使用自己私钥的密码
     */
    private static final String MERC_PRIVATE_FILE_PASSWORD = "197Aa2569";

    /**
     * 请求地址域名
     */
    private static final String HTTP_NET = "https://ysgate.ysepay.com";
    //测试 https://appdev.ysepay.com
    //生产 https://ysgate.ysepay.com

    public static void main(String[] args) throws Exception {
//
        getToken();
    }

    //  微信支付下单接口
    @RequestMapping("/PayShangHuJin")
    public String payWx(WxBizContent wxBizContent) throws Exception {
        return "123";
    }

    //  进件接口(1、资料上送)
    @RequestMapping("/smsc/addCustInfoApply")
    public String addCustInfoApply(
            CustInfo custInfo,
            CrpInfo crpInfo,
            StlAccInfo stlAccInfo,
            BusInfo busInfo,
            String thirdFlowId
    ) throws Exception {
        return new YsfApi().addCustInfoApply(custInfo, crpInfo, stlAccInfo, busInfo, thirdFlowId);
    }

    //  进件接口(2、资料修改)
    @RequestMapping("/smsc/modifyCustInfoApply")
    public String modifyCustInfoApply(
            String sysFlowId,
            CustInfo custInfo,
            CrpInfo crpInfo,
            StlAccInfo stlAccInfo,
            BusInfo busInfo
    ) throws Exception {
        return new YsfApi().modifyCustInfo(sysFlowId, custInfo, crpInfo, stlAccInfo, busInfo);
    }

    //  进件接口(3、图片上送)
    @RequestMapping("/smsc/upload")
    public String imgUpload(
            String filePath,
            String picType,
            String picNm,
            String sysFlowId
    ) throws Exception {
        System.out.println(filePath + "-----------------------------filePath");
        return new YsfApi().imgUpload(filePath, picType, picNm, sysFlowId);
    }

    //  进件接口(4、资料确认)
    @RequestMapping("/smsc/auditCustInfoApply")
    public String auditCustInfoApply(
            String sysFlowId
    ) throws Exception {
        return ysfApi.auditCustInfoApply(sysFlowId);
    }

    //  进件接口(5、资料状态查询)
    @RequestMapping("/smsc/queryCustApply")
    public String queryCustApply(
            String sysFlowId
    ) throws Exception {
        return new YsfApi().queryCustApply(sysFlowId);
    }

    //  合同签约状态查询 接口
    @RequestMapping("/constract/queryAuthInfo")
    public String queryAuthInfo(
            String authId,
            String thirdAuthId
    ) throws Exception {
        return new YsfApi().queryAuthInfo(authId, thirdAuthId);
    }

    //  进件接口 - 签约短信或邮件重发
    @RequestMapping("/sign/sendSmsOrEmailMsg")
    public String sendSmsOrEmailMsg(
            String signId,
            String isSendConMsg
    ) throws Exception {
        return new YsfApi().sendSmsOrEmailMsg(signId, isSendConMsg);
    }

    //  进件接口( 第三大步 合同签约 )
    @RequestMapping("/smsc/sign")
    public String queryCustApply(
            String custId,
            String busOpenType,
            String contractType,
            String isSendConMsg,
            String notifyUrl,
            CodeScanT1FeeAll codeScanT1Fee,
            CodeScanD0Fee codeScanD0Fee,
            String swCardT1Fee,
            String swCardD0Fee
    ) throws Exception {

        return ysfApi.smscSign(
                custId,
                busOpenType,
                contractType,
                isSendConMsg,
                notifyUrl,
                codeScanT1Fee,
                codeScanD0Fee,
                swCardT1Fee,
                swCardD0Fee
        );
    }

    //   MCC码查询2
    @RequestMapping("/scan/mccQuery")
    public String querMccCd(String mccCd, String mercType) throws Exception {
        return new Common().querMccCd(mccCd, mercType);
    }

    //   查询行名行号 GM
    @RequestMapping("/trade/findBankNameAndBankCode")
    public String findBankNameAndBankCode(String cityCode, String bankType, String openBankName, String bankCode) throws Exception {
        return new Common().findBankNameAndBankCode(cityCode, bankType, openBankName, bankCode);
    }

    //  卡bin查询 GM
    @RequestMapping("/trade/findBankBinByBankCardNo")
    public String findBankBinByBankCardNo(String bankCardNo) throws Exception {
        return new Common().findBankBinByBankCardNo(bankCardNo);
    }

    //  通过本接口，可以获取省市区的地区码 GM
    @RequestMapping("/trade/findCmmtAreaInfoList")
    public String findCmmtAreaInfoList(String parentCityCd, String areaLevel, String pageNumber, String pageSize) throws Exception {
        System.out.println(parentCityCd + "---------------------------");
        System.out.println(areaLevel + "---------------------------");
        System.out.println(pageNumber + "---------------------------");
        System.out.println(pageSize + "---------------------------");
        return new Common().findCmmtAreaInfoList(parentCityCd, areaLevel, pageNumber, pageSize);
    }

    //    电子合同模式下，可以通过本接口查询当前电子合同状态
    @RequestMapping("/sign/queryContract")
    public String queryContract(
            String authId
    ) throws Exception {
        return new YsfApi().queryContract(authId);
    }

    //   电子合同下载
    @RequestMapping("/sign/downloadContract")
    public void downloadContract(
            String signId
    ) throws Exception {
        new YsfApi().downloadContract(signId);
    }

    public static String getToken() throws Exception {

        //组装公共请求参数
        Map<String, String> mapDate = new HashMap<String, String>();
        mapDate.put("method", "ysepay.merchant.register.token.get");
        mapDate.put("partner_id", CERT_ID);
        mapDate.put("timestamp", DateUtil.getDateNow());
        mapDate.put("charset", "UTF-8");
        mapDate.put("sign_type", "SM");
        mapDate.put("notify_url", "http://127.0.0.1");
        mapDate.put("version", "3.0");
        mapDate.put("biz_content", "{}");
        //进行参数签名，获取sign
        try {
            String sign = YsPaySignUtils.sign(mapDate);
            log.info("产生的签名sign：" + sign);
            mapDate.put("sign", sign);
        } catch (Exception e) {
            log.info("签名异常：" + e);
        }
        //调用TOKEN获取接口
        String result = HttpRequest.sendPost("https://register.ysepay.com:2443/register_gateway/gateway.do", CommonUtil.mapToString(mapDate));
        if (StringUtil.isBlank(result)) {
            log.info("接口返回为空");
        }

        //返回数据验签
        boolean flag = false;
        try {
            flag = YsPaySignUtils.resultVerify(result, "ysepay_merchant_register_token_get_response");
            if (!flag) {
                throw new Exception("验签失败");
            }
        } catch (Exception e) {
            log.info("验签异常：" + e);
        }
        //解析接口回执，获取token值
        JSONObject response = (JSONObject) JSON.parseObject(result, Feature.OrderedField).get("ysepay_merchant_register_token_get_response");
        String token = response.get("token").toString();
        log.info("TOKEN:" + token);

        return "123";
    }

    /**
     * 格式化当前日期时间字符串
     *
     * @return
     */
    private static String getCurrentDateTime(String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date());
    }

}
